//
//  ZRThirdManager.m
//  简书:https://www.jianshu.com/u/043e94ca450f
//
//  Created by 黄涛 on 2018/8/9.
//  Copyright © 2018年 黄涛(ZR:zero). All rights reserved.
//  第三方(微信.微博.QQ) 支付 登录 管理工具

#import "ZRThirdManager.h"
#import <SVProgressHUD/SVProgressHUD.h>
@interface ZRThirdManager () 

/** 腾讯 身份验证 */
@property (nonatomic , strong) TencentOAuth * txOAuth;
/** 腾讯 权限列表 */
@property (nonatomic , strong) NSArray * txPermissions;


@end

static ZRThirdManager * _manager;

@implementation ZRThirdManager

+ (instancetype)sharedManager{
    
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        
        _manager = [[ZRThirdManager alloc] init];
    });
    
    return _manager;
    
}

#pragma mark - ----------------------- 检测是否安装APP -----------------------
/** 微信 是否安装 */
+ (BOOL)hasWechatApp{ return [WXApi isWXAppInstalled]; }

/** 微博 是否安装 */
+ (BOOL)hasWeiboApp{ return [WeiboSDK isWeiboAppInstalled]; }

/** QQ 是否安装 */
+ (BOOL)hasQQApp{ return [QQApiInterface isQQInstalled]; }



#pragma mark - ----------------------- 登录 -----------------------
/** 微信登录 */
+ (void)weChatLogin:(thirdLoginBlock)success{
    
    _manager.thirdLoginSuccess = success;
    
    // 构造SendAuthReq结构体
    SendAuthReq *req = [[SendAuthReq alloc ] init ];
    req.scope = @"snsapi_userinfo" ;
    req.state = @"123" ;
    
    // 第三方向微信终端发送一个SendAuthReq消息结构
    [WXApi sendReq:req];
}

/** 微博登录 */
+ (void)weiboLogin:(thirdLoginBlock)success{
    
    _manager.thirdLoginSuccess = success;
    
    WBAuthorizeRequest *request = [WBAuthorizeRequest request];
    request.redirectURI = @"https:// main page url";
    request.scope = @"all";
    request.userInfo = @{@"SSO_From": @"SendMessageToWeiboViewController",
                         @"Other_Info_1": [NSNumber numberWithInt:123],
                         @"Other_Info_2": @[@"obj1", @"obj2"],
                         @"Other_Info_3": @{@"key1": @"obj1", @"key2": @"obj2"}};
    [WeiboSDK sendRequest:request];
    
}

/** QQ登录 */
+ (void)QQLogin:(thirdLoginBlock)success{

    _manager.thirdLoginSuccess = success;
    
    if (!_manager.txOAuth) {
        
        _manager.txOAuth = [[TencentOAuth alloc] initWithAppId:k_ZRQQAppKey andDelegate:_manager];
    }
    
    if (!_manager.txPermissions) {
        
        _manager.txPermissions =  [NSArray arrayWithObjects:@"get_user_info", @"get_simple_userinfo", @"add_t", nil];
    }
    
    [_manager.txOAuth authorize:_manager.txPermissions inSafari:NO];
    
}
#pragma mark - ----------------------- 支付 -----------------------
/** 支付宝 支付 */
+ (void)aliPayWithData:(NSString *)data success:(thirdPayBlock)success{
    
    [[AlipaySDK defaultService] payOrder:data fromScheme:k_ZRAliPayAppKey callback:^(NSDictionary *resultDic) {
    
        if ([resultDic[@"resultStatus"] isEqualToString:@"9000"]) {
            
            [SVProgressHUD showSuccessWithStatus:@"支付成功"];
            !success ? : success(resultDic);
            _manager.thirdPaySuccess = success;
            
        }else {
            [SVProgressHUD showErrorWithStatus:@"支付失败"];
        }
        
    }];
}

/** 微信 支付 */
+ (void)wechatPayWithData:(NSDictionary *)data success:(thirdPayBlock)success{
    
    //调起微信支付
    PayReq *req             = [[PayReq alloc] init];
    req.openID              = data[@"appid"];
    req.partnerId           = data[@"partnerid"];
    req.prepayId            = data[@"prepayid"];
    req.nonceStr            = data[@"noncestr"];
    req.timeStamp           = [data[@"timestamp"] intValue];
    req.package             = data[@"package"];
    req.sign                = data[@"sign"];
    [WXApi sendReq:req];
    
    _manager.thirdPaySuccess = success;
}

#pragma mark - ----------------------- 其他方法 -----------------------
/** 微信登录 获取 token */
- (void)getAccessTokenWithCode:(NSString *)code{
    
    NSMutableDictionary *params = [NSMutableDictionary dictionary];
    params[@"appid"] = k_ZRWeChatAppKey;
    params[@"secret"] = k_ZRWeChatAppSecret;
    params[@"code"] = code;
    params[@"grant_type"] = @"authorization_code";
    
    [[ZRNetworkingTool shareTool] requestWithMethod:post_zrRequest url:@"https://api.weixin.qq.com/sns/oauth2/access_token" parameters:params finishedBlock:^(id responseObj, NSError *error) {
        
        [SVProgressHUD dismiss];
        
        if (error || responseObj[@"errmsg"]) {
            [SVProgressHUD showInfoWithStatus:@"登录失败！"];
            return;
        }
        
        NSLog(@"获取微信Token结果 :%@", responseObj);
        
        [[NSUserDefaults standardUserDefaults] setObject:responseObj[@"openid"] forKey:k_ZRWeChatOpenIdKey];
        [[NSUserDefaults standardUserDefaults] synchronize];
        
        /** key: openid  unionid access_token */
        !_manager.thirdPaySuccess ? : _manager.thirdLoginSuccess(responseObj);
        
    }];
    
}


#pragma mark - ----------------------- 代理 -----------------------
/** ------------------------- 微信 代理 ------------------------- */
/** 微信消息回调 */
- (void)onResp:(BaseResp *)resp{
    
    switch (resp.errCode) {
             //操作成功
        case WXSuccess:{
            
            if ([resp isKindOfClass:[PayResp class]]) {
                !_manager.thirdPaySuccess ? : _manager.thirdPaySuccess(@{@"resp":resp});
                
            }else if ([resp isKindOfClass:[SendAuthResp class]]){
                
                SendAuthResp * authRes = (SendAuthResp *)resp;
                [self getAccessTokenWithCode:authRes.code];
                
            }else if ([resp isKindOfClass:[SendMessageToWXReq class]]){
                [SVProgressHUD showSuccessWithStatus:@"分享成功"];
            }
        }break;
             //普通错误
        case WXErrCodeCommon: {
            
            if ([resp isKindOfClass:[PayResp class]]) {
                [SVProgressHUD showInfoWithStatus:@"支付失败"];
            }else if ([resp isKindOfClass:[SendMessageToWXReq class]]){
                [SVProgressHUD showInfoWithStatus:@"分享失败"];
            }else if ([resp isKindOfClass:[SendAuthResp class]]){
                [SVProgressHUD showInfoWithStatus:@"登录失败"];
            }
            
        }break;
             //取消操作
        case WXErrCodeUserCancel:[SVProgressHUD showInfoWithStatus:@"操作取消！"]; break;
             //授权失败
        case WXErrCodeAuthDeny: [SVProgressHUD showInfoWithStatus:resp.errStr]; break;
             //微信不支持
        case WXErrCodeUnsupport: [SVProgressHUD showInfoWithStatus:resp.errStr]; break;
        default: [SVProgressHUD showErrorWithStatus:resp.errStr]; break;
    }
    
}
/** ------------------------- 微博 代理 ------------------------- */

/** 微博客户端请求 */
- (void)didReceiveWeiboRequest:(WBBaseRequest *)request{
    
    
}
/** 微博响应消息回调 */
- (void)didReceiveWeiboResponse:(WBBaseResponse *)response{
    
    switch (response.statusCode) {
            
        case WeiboSDKResponseStatusCodeSuccess:{
            
            if ([response isKindOfClass:[WBAuthorizeResponse class]]) {
                
                [[NSUserDefaults standardUserDefaults] setObject:[(WBAuthorizeResponse *)response userID] forKey:k_ZRCurrentUidKey];
                
                [[NSUserDefaults standardUserDefaults] synchronize];
                
                !_manager.thirdLoginSuccess ? : _manager.thirdLoginSuccess(@{@"userId":[(WBAuthorizeResponse *)response userID]});
                [SVProgressHUD showSuccessWithStatus:@"登录成功"];
            }
                
            if ([response isKindOfClass:[WBSendMessageToWeiboRequest class]]) {
                
                [SVProgressHUD showSuccessWithStatus:@"分享成功"];
            }
             
                
        } break;
            
        case WeiboSDKResponseStatusCodeUserCancel:{
            [SVProgressHUD showInfoWithStatus:@"操作已取消"];} break;
        case WeiboSDKResponseStatusCodeAuthDeny:{
            [SVProgressHUD showInfoWithStatus:@"授权失败"];} break;
        case WeiboSDKResponseStatusCodeShareInSDKFailed:{
            [SVProgressHUD showInfoWithStatus:@"分享失败"];} break;
        default: [SVProgressHUD showInfoWithStatus:@"操作失败"];  break;
    }
    
}
/** ------------------------- QQ 代理 ------------------------- */
/** QQ登录成功 */
- (void)tencentDidLogin{
    
    if (_manager.txOAuth.accessToken && 0 != [_manager.txOAuth.accessToken length])
    {
        //  记录登录用户的OpenID、Token以及过期时间
        NSLog(@"QQ登录成功: accessToken-->%@     openId-->%@",  _manager.txOAuth.accessToken,  _manager.txOAuth.openId);
        
        [[NSUserDefaults standardUserDefaults] setObject:_manager.txOAuth.openId  forKey:k_ZRQQOpenIdKey];
        [[NSUserDefaults standardUserDefaults] synchronize];
        
        !_manager.thirdLoginSuccess ? : _manager.thirdLoginSuccess(@{@"openId" : _manager.txOAuth.openId , @"token":_manager.txOAuth.accessToken});
        
    }
    else
    {
        [SVProgressHUD showInfoWithStatus:@"登录失败"];
        NSLog(@"登录不成功:没有获取token");
    }

    
}

/** QQ登录失败 */
- (void)tencentDidNotLogin:(BOOL)cancelled{
    
    cancelled ? NSLog(@"用户取消了 QQ 登录") : [SVProgressHUD showInfoWithStatus:@"登录失败"];
}

/** QQ 网络故障  */
- (void)tencentDidNotNetWork{
    
    [SVProgressHUD showInfoWithStatus:@"无网络连接 请设置网络"];
    
}



@end
